
var BattleLayer = {

	layer : null,
	upLayer : null,
	bg : null,
	cell_up : null, 
	cell_down : null,
	groundLayer : null,	//  地面层
	tankLayer : null,	//  坦克层
	touchLayer : null,	//  操作层
	
	units : {}, // 战斗单位

    // 建筑血量
    upHp : 0,
    upHpMax : 0,
    downHp : 0,
   	downHpMax : 0,

	isEnding : false, // 结束中

    init : function (layer, upLayer) {
    	this.layer = layer;
    	this.upLayer = upLayer;

    	// 背景
    	var sp = cc.Sprite.create();
    	this.layer.addChild(sp);
    	this.bg = sp;

    	// 地面层
    	this.groundLayer = cc.Node.create();
    	this.layer.addChild(this.groundLayer);

    	// 坦克层
    	this.tankLayer = cc.Node.create();
    	this.layer.addChild(this.tankLayer);

    	// 操作层
    	this.touchLayer = new BattleTouchPanel(0);
    	this.layer.addChild(this.touchLayer);

		// 格子
		sp = cc.Sprite.create('res/battle/cell.png');
		sp.setAnchorPoint(cc.p(0,0));
		sp.setPosition(helper.CELLS_UP_BASE);
		//sp.setVisible(false);
    	this.upLayer.addChild(sp);
    	this.cell_up = sp;

    	sp = cc.Sprite.create('res/battle/cell.png');
		sp.setAnchorPoint(cc.p(0,1));
		sp.setPosition(helper.CELLS_DOWN_BASE);
		//sp.setVisible(false);
    	this.upLayer.addChild(sp);
    	this.cell_down = sp;

	},

	// 设置背景
	setBg : function (image) {
		this.bg.init(image);
		this.bg.setPosition(320, 480);
	},

	// 显示隐藏格子
	showCells : function (isShow) {
		this.cell_up.setVisible(isShow);
		this.cell_down.setVisible(isShow);
	},

    // 开始战斗
    onBattleStart : function() {
    	this.isEnding = false;

    	this.upHp = 200;
    	this.upHpMax = 200;
    	this.downHp = 200;
    	this.downHpMax = 200;

    	for(var id in this.units) {
    		var unit = this.units[id];
    		unit.onStartBattle();
    	}

    	// 操作层
    	this.touchLayer.setTouchEnabled(true);
    },

    // 结束战斗 (frome checkBattleOver)
    onBattleEnd : function(winner) {
       	for(var id in this.units) {
    		var unit = this.units[id];
    		unit.onEndBattle();
    	}

    	// 战斗单位
    	this.removeAllUnits();

    	//* 释放战斗资源
    	// 地面层 在坦克之下
    	this.groundLayer.removeAllChildren(true);
    	
    	// 坦克层
    	this.tankLayer.removeAllChildren(true);

    	// 操作层
    	this.touchLayer.setTouchEnabled(false);	
    },

	createUnit : function (id, type, side, cx, cy, hp, mhp, isAI) {
		if(this.getUnit(id)) {
			cc.log('Battlelayer.createUnit:already exist id:'+id);
			return;
		}

		var unit;
		if (isAI) {
			unit = new AITank(id, type, side, cx, cy, hp, mhp);
		} else {
			unit = new BattleUnit(id, type, side, cx, cy, hp, mhp);
		}

		this.tankLayer.addChild(unit);
		this.units[id] = unit;

		cc.log('createUnit: id:'+id+' type:'+type+' side:'+side+' pos:['+cx+','+cy+']'+' hp:'+hp+'/'+mhp);
	},

	getUnit : function (id) {
		return this.units[id];
	},

	getUnitByCellPos : function (side,cx, cy) {
		for ( var id in this.units ) {
			var tk  = this.units[id];
			if(tk.cx == cx && tk.cy == cy && tk.side == side) return tk;
		};
	},

	removeUnit : function(id) {
		var unit = this.getUnit(id);
		unit.removeFromParent(unit);
		delete this.units[id];
	},

	removeAllUnits : function(id) {
		var ids = [];
		for(var id in this.units) { ids.push(id); }
		for each(var id in ids) { this.removeUnit(id); }
	},

	unitMove : function (cmdStr, id, cx, cy) {
		cc.log('unitMove:'+id);
		unit = this.getUnit(id);
		unit.moveTo(cx, cy);
	},

	// 获取攻击目标
	getAttackTarget : function (unit) {
		// 查找出对面的列 要活的
		var l = [];
		for (var id in this.units) {
			var u = this.units[id];
			if (u.cx == unit.cx && u.side != unit.side && u.id != unit.id && !u.isDead()) l.push(u);
		};
		if(l.length == 0) return null;

		// 取得cy最小的
		var target = l[0];
		for each(var u in l) {
			if (u.id != target.id && u.cy < target.cy) target = u;
		}

		return target;
	},

	// 单位攻击
	onUnitAttack : function (unit) {
		if(this.isEnding) return;

		// 目标
		var target = this.getAttackTarget(unit);
		if (!target) {
			// 打对面建筑
			this._unitAttack(unit, null);
		} else {
			this._unitAttack(unit, target);
		}

	}, 

	_unitAttack : function (srcUnit, dstUnit) {
		/*
		cc.log('_unitAttack:--------')
		cc.dump(data);
		cc.log('_unitAttack:-------- end')
		*/
		var su = srcUnit;   // source unit
        var du = dstUnit;   // target unit, 如果为null, 则打对面建筑
        var isAtkUnit = (du != null);
        
        // 开炮动画
        su.aniAttack();
        
        // 生成子弹
        var b = new BattleBullet(su.side, su.cx, su.cy);
		this.upLayer.addChild(b);
        
        // 子弹目标位置
        var p;
        if(isAtkUnit) p = du.getPosition();
        else p = this._getBulletTargetBuilding(su); 
		b.moveTo(p.x, p.y, _onOver, this);
        
        // 播放开炮音效
        var audioEngine = cc.AudioEngine.getInstance();
        //audioEngine.playEffect('res/music/bomb.wav');
        
        function _onOver (target) {
            // 消除子弹
            b.removeFromParent();
            // 爆炸特效
            FXManager.playParticleSystem('res/fx/toonCloud.plist', this.upLayer, 2.0, p);
            FXManager.playParticleSystem('res/fx/bomb.plist', this.upLayer, 2.0, p);
            FXManager.playParticleSystem('res/fx/dustFlare.plist', this.upLayer, 2.0, p);

            if(isAtkUnit) {
	            // 目标受伤
	            du.aniHurt();
	            // 播放中弹音效
	            //audioEngine.playEffect('res/music/bomb.wav');
	            // 攻击结果
	            //this.handleEffect(data[4]);

	            //* 测试减血
	            du.addHp(-20);
            } else {
            	// 建筑减血
            	var side = (su.side == helper.SIDE_UP) ? helper.SIDE_DOWN : helper.SIDE_UP;
            	this.addBuildingHp(side, -50)
            }


            // 检查是否结束一局
            this.checkGameOver();
        }
	},

	// 子弹打到建筑物上的坐标获取
	_getBulletTargetBuilding : function (u) {
		var p = cc.p(0,0);
		var sz = cc.Director.getInstance().getWinSize();

    	// fix 0 3 4 7列的坐标问题
    	var fix = 0;
		var ll = [0,3,4,7];
		if (ll.indexOf(u.cx) > -1) fix = 15;

    	p.x = u.getPosition().x;
    	if(u.side == helper.SIDE_UP) p.y = 80 - fix;
    	else p.y = sz.height - 80 + fix; 

    	//* 加点随机
    	return p;
	},


	// 处理攻击效果
	handleEffect : function (data) {
		for each(var d in data) {
			cc.log('handleEffect:' + d);
			var type = d[0];
			switch(type) {
				case 'HP': this._handleEffectHP(d);
				case 'BFA': this._handleEffectBF(d, true);
				case 'BFR': this._handleEffectBF(d, false);
			}
		}
	},

	_handleEffectHP : function (d) {
		var id = d[1];
		var hp = d[2];
		var u = this.getUnit(id);
		u.addHp(hp);
	},

	_handleEffectBF : function (d, isAdd) {

	},

	// 增加到地面层
	addToGroundLayer : function (sp) {
		this.groundLayer.addChild(sp);
	},

	removeFromGroundLayer : function (sp) {
		this.groundLayer.removeChild(sp);
	},	

	// 点击TouchLayer
	onClick : function (cx, cy) {
		//cc.log('onClick:'+cx +' '+ cy);
		var tk = this.getUnitByCellPos(helper.SIDE_DOWN, cx, cy);
		if (!tk) {
			return false;
		}
		else {
			// 点击坦克
			tk.onClick();
			return true;
		}
	},

	// 检查是否结束一局
	checkGameOver : function () {
		var res;
		res = this._isAllDead();
		if (!res.isOver) res = this._isBuildingDead();

		//cc.dump(res);
		// 结束
		if (res.isOver && !this.isEnding) {
			this.isEnding = true;

			cc.log('-----------------------')
			cc.log('GameOver')
			cc.log('-----------------------')

			// GameOver发给全部坦克
			for(var id in this.units) {
    			var unit = this.units[id];
    			unit.onGameOver();
    		}

			// 并延后处理
            this.scheduleOnce(function () { 
            	//BattleManager.onBattleEnd(); 
            	getUIMain().openUIBattleResult(true);
            } , 2);
		}
	},

	_isAllDead : function () {
		var isAllDeadUp = true;
		var isAllDeadDown = true;

		for (var id in this.units) {
			var tk = this.units[id];
			if(!tk.isDead()) {
				if(tk.side == helper.SIDE_UP) isAllDeadUp = false;
				if(tk.side == helper.SIDE_DOWN) isAllDeadDown = false;
			}
		}
		//cc.log('isAllDeadUp:'+isAllDeadUp);
		//cc.log('isAllDeadDown:'+isAllDeadDown);
		var isOver = isAllDeadUp || isAllDeadDown;
		var winner = isAllDeadUp ? helper.SIDE_DOWN : helper.SIDE_UP;
		return {isOver:isOver, winner:winner};
	},

	_isBuildingDead : function () {
		var isDeadUp = (this.upHp <= 0);
		var isDeadDown = (this.downHp <= 0);

		var isOver = isDeadUp || isDeadDown;
		var winner = isDeadUp ? helper.SIDE_DOWN : helper.SIDE_UP;
		return {isOver:isOver, winner:winner};
	},

	addBuildingHp : function (side, hp) {
		var p
		if(side == helper.SIDE_UP) {
			this.upHp += hp;
			p = this.upHp / this.upHpMax;
		} else {
			this.downHp += hp;
			p = this.downHp / this.downHpMax;
		}
		getUIBattle().setHp(side, p);
	},

	// 镜头控制功能
	/*
	viewLeftSide : function (isImmediately) {
		this._setView(glb.LEFT_SIDE_BASE_POS, 1, isImmediately);

	},

	viewRightSide : function (isImmediately) {
		this._setView(glb.RIGHT_SIDE_BASE_POS, 1, isImmediately);
	},

	viewAll : function (isImmediately) {
		this._setView(glb.CENTER_BASE_POS, 1, isImmediately);
	},

	_setView : function (lookAtPos, scale, isImmediately) {

		// lookAtPos->layerPos
		var winSize = cc.Director.getInstance().getWinSize();
		var pos = {
			x : -lookAtPos.x + winSize.width / 2,
			y : -lookAtPos.y + winSize.height / 2,
		};

		if (isImmediately) {
			this.layer.setPosition(pos);
			this.layer.setScale(scale);
		} else {
			var time = 0.5;
			this.layer.runAction(cc.MoveTo.create(time, pos));
			this.layer.runAction(cc.ScaleTo.create(time, scale));
		}

	},
	*/

	update : function() {

	},

	// update控制 ------------------
	startUpdate : function(interval) {
    	cc.Director.getInstance().getScheduler().scheduleCallbackForTarget(
    		this, this.update, interval, cc.REPEAT_FOREVER);
	},

	pauseUpdate : function() {
    	cc.Director.getInstance().getScheduler().pauseTarget(this);
	},

	resumeUpdate : function() {
    	cc.Director.getInstance().getScheduler().resumeTarget(this);
	},

	stopUpdate : function() {
    	cc.Director.getInstance().getScheduler().unscheduleCallbackForTarget(this, this.update);
	},

	scheduleOnce : function(callback, timeout) {
    	cc.Director.getInstance().getScheduler().scheduleCallbackForTarget(
    		this, callback, timeout, 0);	// 0:之执行一次
	},


};

